import Vue from 'vue'
import Router from 'vue-router'
import {getUser, setMenu} from '@/utils/session'
import routes from '@/resource/menuConfig'
import NProgress from 'nprogress'

Vue.use(Router)
// 必须在Router之前保存一份menuConfig.js中的值,因为路由的变化会改变menuConfig.js中值
setMenu(routes)
const router = new Router({ routes })

router.beforeEach((to, from, next) => {
  // ...
  NProgress.start()
  // console.log(to)
  // console.log('下面是from,上面是to')
  // console.log(from)
  // console.log(next)
  let token = ''
  let user = getUser()
  // console.log(JSON.stringify(user))
  if (JSON.stringify(user) === 'null' || JSON.stringify(user) !== '{}') {
    token = user.token
    if (token === undefined || token === '') {
      token = user.access_token
    }
  }

  // console.log('token:' + token)
  if (token === '' || token === undefined) {
    // console.log('过来强制跳转:' + to.path + ', token:' + token)
    if (to.path === '/securityLogin') { // 防止无限循环导致栈溢出
      next()
    } else {
      // next({ path: '/login', name: 'login' })
      next({ path: '/securityLogin', name: 'oauth2_login' })
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
